<?php

namespace common\sundries;

class NumberChanger {
    protected array $chinese = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '扒', '玖'];
    protected array $baseUnit = ['', '拾', '佰', '仟'];
    protected array $scaleUnit = ['', '万', '亿', '兆', '京', '垓', '秭', '穰'];

    /**
     * 阿拉伯数字转中文
     * @param string $number
     * @return mixed
     */
    public function Arab2Chinese(string $number) {
        $number = str_split($number, 1);
        $number = array_reverse($number);
        $number = array_chunk($number, 4);

        foreach ($number as &$scale) {
            foreach ($scale as $k => &$base) {
                if ($base) {
                    $base = $this->chinese[$base] . $this->baseUnit[$k];
                } else {
                    if (isset($scale[$k - 1]) && $scale[$k - 1] == $this->chinese[0]) {
                        $base = null;
                    } else {
                        $base = $this->chinese[0];
                    }
                }
            }
        }
        unset($scale, $base);

        foreach ($number as $k => $scale) {
            $scale = array_reverse($scale);
            $result = array_reduce($scale, function ($res, $val) use ($k) {
                $res .= $val;
                return $res;
            }, '');
            $result = rtrim($result, $this->chinese[0]);
            if ($result) {
                $number[$k] = $result . $this->scaleUnit[$k];
            } else {
                $number[$k] = null;
            }
        }

        $number = array_reverse($number);
        return array_reduce($number, function ($res, $val) {
            $res .= $val;
            return $res;
        }, '');
    }
}
